package com.xyht.medicine_management_system.modules.kuaidi.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.kuaidi100.sdk.api.BOrderOfficial;
import com.kuaidi100.sdk.api.LabelV2;
import com.kuaidi100.sdk.api.QueryTrack;
import com.kuaidi100.sdk.contant.ApiInfoConstant;
import com.kuaidi100.sdk.contant.PrintType;
import com.kuaidi100.sdk.core.IBaseClient;
import com.kuaidi100.sdk.pojo.HttpResult;
import com.kuaidi100.sdk.request.*;
import com.kuaidi100.sdk.request.labelV2.CustomReq;
import com.kuaidi100.sdk.response.BaseResponse;
import com.kuaidi100.sdk.utils.SignUtils;
import com.xyht.medicine_management_system.common.util.TimeUtil;
import com.xyht.medicine_management_system.modules.kuaidi.constant.KuaiDi100ConfigConstant;
import com.xyht.medicine_management_system.modules.kuaidi.entity.MmsKuaidiInfo;
import com.xyht.medicine_management_system.modules.kuaidi.entity.resp.*;
import com.xyht.medicine_management_system.modules.kuaidi.entity.KuaidiTemplateParam;
import com.xyht.medicine_management_system.modules.kuaidi.myEnum.KuaidiCompanyEnum;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Component
public class Kuaidi100Util {
    @Resource
    private KuaiDi100ConfigConstant kuaiDi100ConfigConstant;

    /**
     * @description 实时快递查询
     * @create 2024/6/30
     * @author dxn
     */
    public List<KuaiDiQueryResp> queryTrack(MmsKuaidiInfo kuaidiInfo) {
        QueryTrackReq queryTrackReq = new QueryTrackReq();
        QueryTrackParam queryTrackParam = new QueryTrackParam();
        queryTrackParam.setCom(kuaidiInfo.getKuaidiCompany());
        queryTrackParam.setNum(kuaidiInfo.getKuaidiNum());
        queryTrackParam.setResultv2("1");
        queryTrackParam.setPhone(kuaidiInfo.getSendTel());
        String param = new Gson().toJson(queryTrackParam);

        queryTrackReq.setParam(param);
        queryTrackReq.setCustomer(kuaiDi100ConfigConstant.getCUSTOMER());
        queryTrackReq.setSign(SignUtils.querySign(param, kuaiDi100ConfigConstant.getKEY(), kuaiDi100ConfigConstant.getCUSTOMER()));

        IBaseClient baseClient = new QueryTrack();
        try {
            HttpResult result = baseClient.execute(queryTrackReq);
            System.out.println("++++++++++++result"+JSON.toJSONString(result));
            KuaiDiQueryResultResp resultResp = JSON.parseObject(result.getBody(), KuaiDiQueryResultResp.class);
            if (result.getStatus() != 200 || !resultResp.getStatus().equals("200")) {
                return null;
            }
            return resultResp.getData();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @description 自定义模板电子面单
     * @create 2024/7/1
     * @author dxn
     */
    public KuaiDiPrintResp customTemplate(MmsKuaidiInfo kuaidiInfo) {
        CustomReq customReq = new CustomReq();

        customReq.setPrintType(PrintType.IMAGE);
        customReq.setTempId("98f21a9d73614be4b3ca5180f4f2eff4");

        Map<String, Object> customParam = new HashMap<>();
        customParam.put("printTime", TimeUtil.Dateformat(new Date()));
        customParam.put("orderId", kuaidiInfo.getOrderId());
        customParam.put("kuaiDiNum", kuaidiInfo.getKuaidiNum());
        customParam.put("recName", kuaidiInfo.getRecName());
        customParam.put("recTel", kuaidiInfo.getRecTel());
        customParam.put("recAddr", kuaidiInfo.getRecAddr());
        customParam.put("sendName", kuaidiInfo.getSendName());
        customParam.put("sendTel", kuaidiInfo.getSendTel());
        customParam.put("sendAddr", kuaidiInfo.getSendAddr());
        customParam.put("remark", kuaidiInfo.getRemark());
        customParam.put("kuaiDiCompany", KuaidiCompanyEnum.fromCode(kuaidiInfo.getKuaidiCompany()).getCompanyName());
        customReq.setCustomParam(customParam);

        String param = new Gson().toJson(customReq);
        String t = System.currentTimeMillis() + "";

        PrintReq printReq = new PrintReq();
        printReq.setT(t);
        printReq.setKey(kuaiDi100ConfigConstant.getKEY());
        printReq.setSign(SignUtils.printSign(param, t, kuaiDi100ConfigConstant.getKEY(), kuaiDi100ConfigConstant.getSECRET()));
        printReq.setMethod(ApiInfoConstant.CUSTOM);
        printReq.setParam(param);

        IBaseClient baseClient = new LabelV2();
        try {
            HttpResult result = baseClient.execute(printReq);
            System.out.println("++++++++++++result"+JSON.toJSONString(result));
            KuaiDiPrintResultResp resultResp = JSON.parseObject(result.getBody(), KuaiDiPrintResultResp.class);
            if (result.getStatus() != 200 || !resultResp.isSuccess()) {
                return null;
            }
//            return JSONObject.parseObject(result.getData().toString()).getString("label");
            return resultResp.getData();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @description 商家寄件下单
     * @create 2024/7/1
     * @author dxn
     */
    public KuaidiSendResultResp kuaidiSend(MmsKuaidiInfo kuaidiInfo, List<Map<String, Object>> list) throws Exception {
        PrintReq printReq = new PrintReq();
        BOrderReq bOrderReq = new BOrderReq();
        bOrderReq.setKuaidicom(kuaidiInfo.getKuaidiCompany());
        bOrderReq.setSendManName(kuaidiInfo.getSendName());
        bOrderReq.setSendManMobile(kuaidiInfo.getSendTel());
        bOrderReq.setSendManPrintAddr(kuaidiInfo.getSendAddr());
        bOrderReq.setRecManName(kuaidiInfo.getRecName());
        bOrderReq.setRecManMobile(kuaidiInfo.getRecTel());
        bOrderReq.setRecManPrintAddr(kuaidiInfo.getRecAddr());
        bOrderReq.setCallBackUrl(kuaiDi100ConfigConstant.getORDER_CALLBACK());
        bOrderReq.setSalt(kuaiDi100ConfigConstant.getSALT());
        bOrderReq.setWeight(kuaidiInfo.getSendWeight());
        bOrderReq.setRemark(kuaidiInfo.getRemark());
        bOrderReq.setOp("1"); //是否开启订阅功能 0：不开启(默认) 1：开启
        bOrderReq.setPollCallBackUrl(kuaiDi100ConfigConstant.getSTATUS_CALLBACK());

        String t = String.valueOf(System.currentTimeMillis());
        String param = new Gson().toJson(bOrderReq);

        printReq.setKey(kuaiDi100ConfigConstant.getKEY());
        printReq.setSign(SignUtils.printSign(param, t, kuaiDi100ConfigConstant.getKEY(), kuaiDi100ConfigConstant.getSECRET()));
        printReq.setT(t);
        printReq.setParam(param);
        printReq.setMethod(ApiInfoConstant.B_ORDER_OFFICIAL_ORDER_METHOD);
        System.out.println(printReq);
        IBaseClient bOrder = new BOrderOfficial();
        try {
            HttpResult result = bOrder.execute(printReq);
            System.out.println("+++++++++++++result" + JSON.toJSONString(result.getBody()));
            KuaidiSendResultResp resultResp = JSON.parseObject(result.getBody(), KuaidiSendResultResp.class);
            if (result.getStatus() != 200 || !resultResp.isResult()) {
                packageResult(list, kuaidiInfo.getOrderId(), resultResp.getMessage(),false);
                return null;
            }
            return resultResp;
        } catch (Exception e) {
            e.printStackTrace();
            packageResult(list, kuaidiInfo.getOrderId(), "程序异常",false);
            return null;
        }
    }

    private void packageResult(List<Map<String, Object>> list, String orderId, String msg,boolean isSuccess) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("msg", msg);
        map.put("orderId", orderId);
        map.put("result", isSuccess);
        list.add(map);
    }

    /**
     * @description 取消下单
     * @create 2024/7/4
     * @author dxn
     */
    public KuaidiCancelResp kuaidiCancel(MmsKuaidiInfo kuaidiInfo) {
        PrintReq printReq = new PrintReq();
        BOrderCancelReq bOrderCancelReq = new BOrderCancelReq();
        bOrderCancelReq.setTaskId(kuaidiInfo.getKuaidiTaskId());
        bOrderCancelReq.setOrderId(kuaidiInfo.getKuaidiOrderId());
        bOrderCancelReq.setCancelMsg(kuaidiInfo.getKuaidiCancelMsg());

        String t = String.valueOf(System.currentTimeMillis());
        String param = new Gson().toJson(bOrderCancelReq);

        printReq.setKey(kuaiDi100ConfigConstant.getKEY());
        printReq.setSign(SignUtils.printSign(param, t, kuaiDi100ConfigConstant.getKEY(), kuaiDi100ConfigConstant.getSECRET()));
        printReq.setT(t);
        printReq.setParam(param);
        printReq.setMethod(ApiInfoConstant.B_ORDER_OFFICIAL_CANCEL_METHOD);

        IBaseClient bOrder = new BOrderOfficial();
        KuaidiCancelResp kuaidiCancelResp = new KuaidiCancelResp();
        kuaidiCancelResp.setResult(false);
        try {
            BaseResponse result = bOrder.executeToObject(printReq);
            kuaidiCancelResp.setResult(result.isResult());
            kuaidiCancelResp.setMessage(result.getMessage());
            return kuaidiCancelResp;
        } catch (Exception e) {
            e.printStackTrace();
            return kuaidiCancelResp;
        }
    }

}
